package com.wingsfrog.puzzle.controller;

import com.google.gson.Gson;
import com.wingsfrog.puzzle.modules.entity.User;
import com.wingsfrog.puzzle.service.PictureService;
import com.wingsfrog.puzzle.service.UserService;
import com.wingsfrog.puzzle.util.wechat.WechatConst;
import com.wingsfrog.puzzle.util.wechat.WeiXinUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Objects;

@Controller
@RequestMapping(value = "users")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    PictureService pictureService;

    @Value("${spring.profiles.active}")
    String profile;

    private Logger logger = Logger.getLogger(UserController.class);

    @RequestMapping(value = "entrance",method = {RequestMethod.GET})
    public void entrance(HttpServletResponse response,
                         HttpServletRequest request,
                         @RequestParam(value = "gameId", required = false) Integer gameId) throws IOException {
        String _url = null;
        if (gameId == 1)
            _url = WechatConst.createOauthUrl(WechatConst.redirectUri,
                    "http://wingsfrog.com/p/puzzle?picId=0");
        else if (gameId == null) // TODO 跳转到平台首页
            _url = WechatConst.createOauthUrl(WechatConst.redirectUri,
                    "http://wingsfrog.com");
        logger.info("_url=" + _url);
        response.sendRedirect(_url);
    }

    /**
     * @api {post} /users/wxLogin 用户登录
     * @apiParam {String} code 微信返回的token
     * @apiParam {String} state 微信返回的数据
     * @apiSuccess {String} token 登录成功返回一个用户登录的token
     */
    @RequestMapping(value = "wxLogin", method = {RequestMethod.GET})
    @Transactional
    public void wxLogin(HttpServletResponse response,
                        HttpServletRequest request,
                        @RequestParam("code") String code,
                        @RequestParam("state") String state,
                        @RequestParam(value = "refereeId", required = false) Integer refereeId
    ) throws IOException {
        WeiXinUtil.ParseCode parseCode = WeiXinUtil.getUserTokenByCode(code);
        if (parseCode == null) return;

        logger.info("seesionId:"+request.getSession().getId());
        logger.info("cookieId:"+(new Gson()).toJson(request.getCookies()));

        WeiXinUtil.UserInfo userInfo = WeiXinUtil.getUserInfo(parseCode.access_token, parseCode.openid);
        if (userInfo == null) {
            logger.error("不能从微信获取用户的userInfo");
            String _url = WechatConst.createOauthUrl(WechatConst.redirectUri);
            response.sendRedirect(_url);
            return;
        }
        User user;
        if (userService.notExist(parseCode.openid)) {
            user = new User();
            user.setOpenId(userInfo.openid);
            if (refereeId != null) user.setRefereeId(refereeId); // 记录引荐人
        } else {
            user = userService.getByOpenId(parseCode.openid);
//            userService.updateLoginTime(parseCode.openid);
        }
        user.setAvatar(userInfo.headimgurl);
        user.setNickname(userInfo.nickname);
        user.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
        user.setCity(userInfo.city);
        user.setProvince(userInfo.province);
        user.setCountry(userInfo.country);
        user.setSex(userInfo.sex);
        user.setLanguage(userInfo.language);
        user.setUnionid(userInfo.unionid);
        userService.saveUser(user);

        logger.info("userId=" + user.getId());
        logger.info("url=" + state);
        request.getSession().setAttribute("userId", user.getId());
        if (state.startsWith("http://wingsfrog.com/"))
            response.sendRedirect(String.format("%s&userId=%d", state, user.getId()));
        else
            response.sendRedirect("http://wingsfrog.com/puzzle");
    }

    @RequestMapping(value = "test", method = {RequestMethod.GET})
    @ResponseBody
    public void test(@RequestParam("userId") Integer userId,
                     HttpServletRequest request) {
        if (Objects.equals(profile, "prod")) return;
        request.getSession().setAttribute("userId", userId);
    }
}
